package com.my.hotel.controller.serverPage;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.my.hotel.entity.Hd;
import com.my.hotel.entity.KfRoom;
import com.my.hotel.entity.KfType;
import com.my.hotel.entity.serverPage.Article;
import com.my.hotel.entity.User;
import com.my.hotel.entity.serverPage.JdUser;
import com.my.hotel.entity.serverPage.UserLike;
import com.my.hotel.entity.vo.ProductRomVo;
import com.my.hotel.mapper.ArticleMapper;
import com.my.hotel.mapper.KfRoomMapper;
import com.my.hotel.service.HdService;
import com.my.hotel.service.KfRoomService;
import com.my.hotel.service.KfTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * author:lwj
 * date: 2022/8/31 14:32
 */
@Controller
@RequestMapping(value = "/utils", produces = "text/html;charset=utf-8")
@Slf4j
public class UtilsController {
    @Autowired
    public JsonObject jsonObject;
    @Autowired
    public ArticleMapper articleMapper;
    @Autowired
    private KfRoomService kfRoomService;
    @Autowired
    private HdService hdService;
    @Autowired
    private KfTypeService kfTypeService;
    @Autowired
    private KfRoomMapper kfRoomMapper;


    // 验证码图片的宽度。
    private int width = 60;
    // 验证码图片的高度。
    private int height = 20;
    // 验证码字符个数
    private int codeCount = 4;
    private int x = 0;
    // 字体高度
    private int fontHeight;
    private int codeY;


    char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    /**
     * 初始化验证图片属性
     */
    public void initxuan() throws ServletException {
        // 从web.xml中获取初始信息
        // 宽度
        String strWidth = "80";
        // 高度
        String strHeight = "30";
        // 字符个数
        String strCodeCount = "4";
        // 将配置的信息转换成数值
        try {
            if (strWidth != null && strWidth.length() != 0) {
                width = Integer.parseInt(strWidth);
            }
            if (strHeight != null && strHeight.length() != 0) {
                height = Integer.parseInt(strHeight);
            }
            if (strCodeCount != null && strCodeCount.length() != 0) {
                codeCount = Integer.parseInt(strCodeCount);
            }
        } catch (NumberFormatException e) {
        }
        x = width / (codeCount + 1);
        fontHeight = height - 2;
        codeY = height - 4;
    }


    @GetMapping("/forward/{url}")
    public String Forward(@PathVariable String url) {
        return "serverPage/" + url;
    }

    @RequestMapping("/varifyCode")
    public void varifyCode(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, java.io.IOException {
        initxuan();
        // 定义图像buffer
        BufferedImage buffImg = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();   //  创建一个画布
        // 创建一个随机数生成器类
        Random random = new Random();
        // 将图像填充为白色
        g.setColor(Color.WHITE);
        //绘制一个矩形
        g.fillRect(0, 0, width, height);
        // 创建字体，字体的大小应该根据图片的高度来定。
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        // 设置字体。
        g.setFont(font);
        // 画边框。
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        // 随机产生9条干扰线，使图象中的认证码不易被其它程序探测到。
        g.setColor(Color.BLACK);
        for (int i = 0; i < 9; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        // randomCode用于保存随机产生的验证码，以便用户登录后进行验证。
        StringBuffer randomCode = new StringBuffer();
        int red = 0, green = 0, blue = 0;
        // 随机产生codeCount数字的验证码。
        for (int i = 0; i < codeCount; i++) {
            // 得到随机产生的验证码数字。
            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
            // 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。
            red = random.nextInt(255);   //   颜色值 范围 :  0-255
            green = random.nextInt(255);
            blue = random.nextInt(255);
            // 用随机产生的颜色将验证码绘制到图像中。
            g.setColor(new Color(red, green, blue));
            g.drawString(strRand, (i + 1) * x, codeY);   //图片上绘制字
            // 将产生的四个随机数组合在一起。用于存session
            randomCode.append(strRand);
        }

        // **********将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        session.setAttribute("validateCode", randomCode.toString());

        //允许跨域访问
        resp.setHeader("Access-Control-Allow-Origin", "*");
        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        //设置响应的数据类型：  image/jpeg, 这样浏览器会以图像显示
        resp.setContentType("image/jpeg");
        //resp.setContentType("text/html;charset=utf-8");
        // 将图像输出到Servlet输出流中。
        //PrintWriter out=resp.getWriter();
        ServletOutputStream sos = resp.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.close();
    }

    @GetMapping(value = "/checkingVarifyCode", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String checkingVarifyCode(@RequestParam String varifyCode, HttpServletRequest req) {
        HttpSession session = req.getSession();
        String validateCode = (String) session.getAttribute("validateCode");
        log.debug("validateCode=" + validateCode);
        System.out.println("validateCode = " + validateCode);
        String trim1 = validateCode.toLowerCase().trim();
        String trim = varifyCode.toLowerCase().trim();
        boolean b = trim.equals(trim1);
        return b ? "true" : "false";
    }

    /**
     * 通过一次跳转获得isLogin
     *
     * @param url     需要跳转的路径
     * @param isLogin 0 登录 1 注册
     * @param req
     * @return
     */
    @GetMapping(value = "/forwardToLogin/{url}", produces = "text/html;charset=utf-8")
    public String forwardToLogin(@PathVariable String url, Integer isLogin, HttpServletRequest req) {
        //页面跳转清除loginmsg
        req.getSession().removeAttribute("loginmsg");
        req.setAttribute("isLogin", isLogin);
        return "serverPage/" + url;
    }


    //list 测试数据
    @GetMapping(value = "/forward/index/{index}", produces = "text/html;charset=utf-8")
    public String forwardToLogin(Integer page, @PathVariable int index, Model model) {
        if (page == null || page == 0) {
            page = 1;
        }
        PageInfo hashMaps =
                hotelProducts(page, index);
        String string = JSON.toJSONString(hashMaps);
        System.out.println("jdLIst");
        System.out.println(string);
        System.out.println("article2");
        model.addAttribute("JdList", hashMaps);
        //废弃
//        Map hotelDetails = hotelDetails(2);  //通过酒店id 获取酒店详情  //之后最好存入redis或者mongodb

        List<Article> article = getArticle2(0);
        model.addAttribute("article", article);
        int i = articleMapper.countLikeNum();
        model.addAttribute("remarkCount", i); //点评总数

        return "serverPage/index";
    }


    /**
     * 伪造酒店商品数目
     *
     * @param index 商品数目
     * @return
     */

    public PageInfo hotelProducts(int page, int index) {
        PageHelper.startPage(page, index);
        List<KfRoom> list1 = kfRoomMapper.getList();
        System.out.println(list1);
        PageInfo<KfRoom> info = new PageInfo(list1);
        List<KfRoom> list = info.getList();
        ArrayList arrayList = new ArrayList();
        for (KfRoom room : list) {
            ProductRomVo p = new ProductRomVo();


            int kfTypeId = room.getKfTypeId();
            KfType kfTypeById = kfTypeService.getKfTypeById(kfTypeId);

            int hdId = room.getHdId();
            Hd hdById = hdService.getHdById(hdId);
            p.setId(room.getId());
            p.setImg(kfRoomService.getUrlByRoomId(room.getId()));

            p.setStyle(kfTypeById == null ? "无" : kfTypeById.getTypeName());
            p.setArea(room.getKfArea());
            p.setBreakfast(room.getKfDesc());
            p.setNumofpeople("两人");
            p.setPolicy("今天12:00时前免费取消");
            p.setMoney(room.getKfPrice());
            if (hdById != null) {
                p.setDiscountType(hdById.getHdType());
                p.setDiscount(hdById.getHdYh());
            } else {
                p.setDiscountType("2");
                p.setDiscount(0.0);
            }

            arrayList.add(p);
        }

        info.setList(arrayList);
        return info;
//        ArrayList<HashMap> hashMaps = new ArrayList<HashMap>();
//        for (int i = 0; i < index; i++) {
//            HashMap map = new HashMap();
//            map.put("id",i+1);
//            map.put("img","/img/002.jpg");
//            map.put("style","经济大床房");
//            map.put("type","大床");
//            map.put("breakfast","无早餐");
//            map.put("numofpeople","两人");
//            map.put("policy","今天12:00时前免费取消");
//            map.put("money","54900");  //必须为整数
//            map.put("discountType",0); //0 减免 1 折扣 2 无折扣
//            map.put("discount",20); //0 减免 1 折扣 2 为0 必须为整数
//            hashMaps.add(map);
//        }
//        return  hashMaps;
    }

//    @RequestMapping("/hotelDetails")
////    @ResponseBody

    // @RequestMapping("/test2")
    List getArticle2(int id) {
//        List<Article> childById = articleMapper.getChildById(id);
        List<Article> childById = articleMapper.getChildById(id);
        String string = JSON.toJSONString(childById);
        System.out.println(string);
        return childById;


    }

    //    没有子评论专门查看子评论 暂时关闭
//    @RequestMapping("/test3")
//    Article getArticle3(Integer id){
//        Article childById = articleMapper.getArticle(id);
//        String string = JSON.toJSONString(childById);
//        System.out.println(string);
//        return childById;
//    }
    Article getArticle() {
        Article article = new Article(0);
        ArrayList<Article> lists = getLists();
        getList(article, lists);
        return article;
    }

    Article getList(Article article, ArrayList<Article> lists) {
        int articleId = article.getArticleId();

        ArrayList<Article> collect = (ArrayList<Article>) lists.stream().filter(e -> {
            return e.getParentId() == articleId;
        }).collect(Collectors.toList());
        //todo 这还应该判断用户status article的state  有没有权限 返回null  这里是模拟数据我就不写了
        if (collect.size() == 0) {
            return null;
        }

        for (Article a : collect) {
            getList(a, lists);
            int userId = a.getFormUserId();  // todo 这里数据库或redis读写 可能碰到读不出的问题 注意判空
//             a.setFormUser(users.get(userId));
        }
        article.setChild(collect);
        return article;
    }

    private static List<User> users;
    private static List<UserLike> userLikes; //todo 最好搞可复用的嵌套插入这里不想搞 先这样

    static { // todo 这里取出的user 因为设计到反复读取 可以放在redis 这里是模拟数据我就不写了
        users = new ArrayList<User>();
        User user1 = new User(1, "南屏晚钟", "../../../img/005.jpg", 0);
        User user2 = new User(1, "画外人", "../../../img/004.jpg", 0);
        User user3 = new User(1, "如果说", "../../../img/003.jpg", 0);
        User user4 = new User(1, "蚂蚁颂", "../../../img/002.jpg", 0);
        User user5 = new User(1, "丝绸", "../../../img/001.jpg", 0);
        users.add(null);
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        users.add(user5);

//todo 这里也是 点赞字段少推荐放redis  这里不想搞 先这样，之后在写点赞
        UserLike u11 = new UserLike(1, 10001);
        UserLike u12 = new UserLike(1, 10002);
        UserLike u13 = new UserLike(1, 10003);
        UserLike u2 = new UserLike(2, 10001);
        UserLike u3 = new UserLike(3, 10001);
        UserLike u4 = new UserLike(4, 10001);
        UserLike u5 = new UserLike(5, 10001);
    }

    private ArrayList<Article> getLists() {
        ArrayList<Article> articles = new ArrayList<Article>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a HH:mm:ss");
        Date date1 = new Date(2022, 11, 20, 12, 20, 22);
        Article art1 = new Article(10001, "我爱喝白开水，天天喝", null, 1, sdf.format(date1), 12, 1, 0, null, 5);

        Date date2 = new Date(2022, 11, 20, 12, 2, 19);
        Article art2 = new Article(10002, "", null,
                2, sdf.format(date2), 12, 1, 0, null, 4);

        Date date3 = new Date(2022, 11, 20, 12, 44, 55);
        Article art3 = new Article(10003, "老人很满意,前台和客房服务都很热情",
                null, 3, sdf.format(date3), 12, 1, 0, null, 0);

        Date date4 = new Date(2022, 11, 20, 13, 19, 18);
        Article art4 = new Article(10004, "#卫生间干净 #客房干净 #服务很热情 #态度热情 #风格独特。空间体验好 #安全放心 #锁链不错 入住体验非常不错，老人很满意，前台和客房服务都很热情。", null, 4, sdf.format(date4), 12, 1, 10001, null, 5);

        Date date5 = new Date(2022, 11, 20, 13, 24, 22);
        Article art5 = new Article(10005, "赏你五颗星", null, 1, sdf.format(date5), 12, 1, 10001, null, 5);

        Date date6 = new Date(2022, 11, 21, 15, 26, 2);
        Article art6 = new Article(10006, "我也这么觉得呢", null, 5, sdf.format(date6), 12, 1, 10004, null, 5);

        Date date7 = new Date(2022, 11, 21, 17, 2, 59);
        Article art7 = new Article(10007, "我也这么", null, 1, sdf.format(date7), 12, 1, 10002, null, 5);

        Date date8 = new Date(2022, 11, 22, 4, 45, 22);
        Article art8 = new Article(10008, "科學研究表明，開水庫可以直接喝，應爲太湯了", null, 1, sdf.format(date8), 12, 1, 10001, null, 5);

        Date date9 = new Date(2022, 11, 22, 12, 20, 23);
        Article art9 = new Article(10009, "你个弯弯，投降吧", null, 1, sdf.format(date9), 12, 1, 10008, null, 5);
        articles.add(art1);
        articles.add(art2);
        articles.add(art3);
        articles.add(art4);
        articles.add(art5);
        articles.add(art6);
        articles.add(art7);
        articles.add(art8);
        articles.add(art9);
        return articles;
    }

    @RequestMapping(value = "/delArticleById")
    @ResponseBody
    public String delArticleById(HttpServletRequest req,
            @RequestParam("delId") Integer delId, @RequestParam("formId") Integer formId) {
        if (delId == null || delId == 0||formId==null||formId==0) {
            return "0";
        }
        Article one = articleMapper.getOne(delId);
        if (one.getArticleId() == null) {
            return "0";
        }
        Article form = articleMapper.getOne(formId);
        if (form.getArticleId() == null) {
            return "0";
        }


        JdUser userInfo = (JdUser) req.getSession().getAttribute("userInfo");
        //评论的人和主评论的人可以删除
        if((userInfo.getId()==one.getFormUserId())||(userInfo.getId()==form.getFormUserId())){
            articleMapper.delOneById(delId);
            return  "1";
        }else{
            return "2";
        }

    }

}
